<template>
  <div class="">
    <el-dialog
      v-model="addEditInfo.openObj.visible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <template #header>
        <div class="dialog_title">
          <div class="blueLine"></div>
          <div class="title">
            {{ addEditInfo.openObj.openTitle }}
            <el-tag
              v-if="
                addEditInfo.openObj.openType != 'return' &&
                addEditInfo.openObj.openKey == 'detail'
              "
              :type="
                addEditInfo.formInfo.enableFlag == 0 ||
                addEditInfo.formInfo.enableFlag == 3 ||
                addEditInfo.formInfo.enableFlag == 4
                  ? 'danger'
                  : addEditInfo.formInfo.enableFlag == 1
                  ? 'warning'
                  : addEditInfo.formInfo.enableFlag == 2
                  ? ''
                  : 'success'
              "
              >{{
                filterStatus(
                  addEditInfo.formInfo.enableFlag,
                  "documentStatus",
                  "id",
                  "langKey"
                )
              }}</el-tag
            >
          </div>
        </div>
      </template>
      <el-form
        :model="addEditInfo.formInfo"
        ref="addEditInfoRef"
        label-position="right"
        label-width="auto"
      >
        <el-row :gutter="20">
          <el-col
            v-for="item in addEditInfo.formItems"
            :key="item.prop"
            :span="item.span"
          >
            <el-form-item
              :label="item.label"
              :prop="item.prop"
              :rules="item && item.rules"
            >
              <component
                v-if="item.type == 'el-select'"
                :ref="item.ref"
                :filterable="item.filterable"
                style="width: 100%"
                :is="item.type"
                v-model="addEditInfo.formInfo[item.prop]"
                v-bind="item.attrs"
                v-on="item.events"
                :disabled="getDisAbled(addEditInfo.openObj.openKey, item.attrs.disabled)"
              >
                <el-option
                  v-for="option in item.options"
                  :key="option[item.optionProps.key]"
                  :label="option[item.optionProps.label]"
                  :value="option[item.optionProps.value]"
                ></el-option>
              </component>

              <component
                v-else-if="item.type === 'el-tree-select'"
                :ref="item.ref"
                :filterable="item.filterable"
                style="width: 100%"
                :is="item.type"
                v-model="addEditInfo.formInfo[item.prop]"
                v-on="item.events"
                v-bind="item.attrs"
                :data="item.options"
                :props="item.optionProps"
                :disabled="getDisAbled(addEditInfo.openObj.openKey, item.attrs.disabled)"
              ></component>

              <component
                v-else
                :filterable="item.filterable"
                style="width: 100%"
                :ref="item.ref"
                :is="item.type"
                v-model="addEditInfo.formInfo[item.prop]"
                v-on="item.events"
                v-bind="item.attrs"
                :disabled="getDisAbled(addEditInfo.openObj.openKey, item.attrs.disabled)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex_title">
        <div class="left_title">
          <span>
            {{
              addEditInfo.openObj.openKey != "add"
                ? `${addEditInfo.openObj.tableTitle}`
                : `${t("receiveAndBack.waiting")} ${addEditInfo.openObj.tableTitle}`
            }}
          </span>

          （{{ addEditInfo.tableData.length }}）
        </div>

        <div
          v-if="
            addEditInfo.openObj.openKey != 'detail' &&
            addEditInfo.openObj.openKey != 'return'
          "
        >
          <el-button type="primary" plain @click="openAssetsListDialog">{{
            t("button.add")
          }}</el-button>
        </div>

        <div v-if="addEditInfo.openObj.openKey == 'detail'">
          <ExportButton
            :columns="columns"
            :data="addEditInfo.tableData"
            :filename="`${addEditInfo.openObj.tableTitle}` + `(${getNowDate()})`"
          ></ExportButton>
        </div>
      </div>
      <div class="table_area">
        <el-table
          ref="assetsTableRef"
          style="width: 100%"
          height="400"
          :data="addEditInfo.tableData"
          @selection-change="handleToBeSelection"
          @row-click="handleRowChick"
          :row-class-name="getRowClass"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            v-if="
              addEditInfo.openObj.openKey == 'edit' ||
              addEditInfo.openObj.openKey == 'add'
            "
            :label="t('tableColumns.operation')"
            align="center"
            fixed
            :width="appStore.language == 'zh' ? 80 : 90"
          >
            <template #default="{ row }">
              <div class="operate_link_btn">
                <el-link
                  type="danger"
                  :underline="false"
                  :icon="Delete"
                  @click="delAssets(row)"
                  >{{ t("button.delete") }}</el-link
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column
            v-if="addEditInfo.openObj.openKey == 'return'"
            type="selection"
            width="55"
          />
          <template v-for="(item, index) in columns" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
              :label="t(`tableColumns.${item.langKey}`)"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <div
                  v-if="item.prop == 'assetsCode'"
                  :style="{
                    color: colors.primaryColor,
                    cursor: item.isclick ? 'pointer' : '',
                  }"
                  @click.native.stop="openAssetsDetail(row)"
                >
                  {{ row.assetsCode }}
                </div>
                <el-tag
                  v-else-if="item.prop == 'enableFlag'"
                  :type="
                    row.enableFlag == 0
                      ? 'success'
                      : row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? 'warning'
                      : 'danger'
                  "
                >
                  {{ row.enableFlagName }}
                </el-tag>
                <span v-else>{{ row[item.prop] || "无" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <template
            v-if="
              addEditInfo.openObj.openKey == 'add' ||
              addEditInfo.openObj.openKey == 'edit' ||
              addEditInfo.openObj.openKey == 'reapply'
            "
          >
            <el-button
              type="primary"
              @click="submitAddEditInfo"
              :loading="addEditInfo.openObj.addLoading"
              >{{ t("common.confirm") }}</el-button
            >
          </template>
          <template v-else-if="addEditInfo.openObj.openKey == 'return'">
            <el-button type="warning" plain @click="returnAssets">{{
              t("button.return")
            }}</el-button>
          </template>
          <el-button @click="cancelAddEditInfo">
            {{
              addEditInfo.openObj.openKey == "add"
                ? t("common.cancel")
                : t("common.close")
            }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加资产列表    -->
    <assets
      v-if="canUseAddInfo.openObj.visible"
      ref="assetsDialogRef"
      :can-use-add-info="canUseAddInfo"
      @submitSend="getSubmitSend"
      :selected-assets="getSelectedAssets()"
      @queryCanUseAssetsData="getCanUseAssetsData"
    ></assets>

    <detail
      v-if="assetsDetailInfo.openObj.visible"
      :asset-detail-info="assetsDetailInfo"
    ></detail>
  </div>
</template>

<script setup name="ashAddOrEdit">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import useAppStore from "@/store/modules/app";
const appStore = useAppStore();
import { Delete } from "@element-plus/icons-vue";
import colors from "@/assets/styles/variables.module.scss";
import detail from "./detail.vue"; //资产详情
import assets from "./assets.vue"; //可选资产列表
import { assetsColums } from "@/utils/table/columns";
import ExportButton from "../file/exportButton.vue";
const { proxy } = getCurrentInstance();
const emit = defineEmits([
  "submitAddEditInfo",
  "cancelAddEditInfo",
  "getCanUseAssetsData",
  "returnAssets",
]);

const props = defineProps({
  addEditInfo: {
    type: Object,
    default: true,
  },
});

const columns = assetsColums;
const addEditInfoRef = ref(null); //表单dom，用于refs和reset
const assetsDialogRef = ref(null); //资产选择的对话框
const assetsTableRef = ref(null); //表格选择dom
const assetsSelection = ref([]); //选择的资产
const resetAddOrEdit = () => {
  if (addEditInfoRef.value) {
    nextTick(() => {
      // 清空校验
      addEditInfoRef.value.clearValidate();
    });
  }
};
//确定提交
const submitAddEditInfo = () => {
  proxy.$refs.addEditInfoRef.validate((valid) => {
    if (!valid) return;
    emit("submitAddEditInfo", {
      info: props.addEditInfo.formInfo,
      infoSub: proxy.addEditInfo.tableData,
      delSub: proxy.addEditInfo.delList,
    });
    console.log("真的提交数据", proxy.addEditInfo.tableData);
  });
};
//取消提交
const cancelAddEditInfo = () => {
  resetAddOrEdit();
  if (proxy.addEditInfo.tableData.length > 0) {
    //如果有数据需要清空
    proxy.addEditInfo.tableData = [];
    assetsSelection.value = [];
  }
  emit("cancelAddEditInfo");
};
//返还资产
const returnAssets = () => {
  emit("returnAssets", {
    info: props.addEditInfo.formInfo,
    infoSub: assetsSelection.value,
  });
};

//删除资产
const delAssets = (row) => {
  if (
    row.state &&
    row.state != 0 &&
    !props.addEditInfo.delList.some((item) => item.assetsId === row.assetsId)
  ) {
    const obj = { ...row, state: 2 };
    props.addEditInfo.delList.push(obj);
  }
  const index = proxy.addEditInfo.tableData.findIndex(
    (item) => item.assetsId === row.assetsId
  );
  if (index !== -1) {
    proxy.addEditInfo.tableData.splice(index, 1);
  }
};

//表格点击与选择
const handleToBeSelection = (val) => {
  assetsSelection.value = val;
};
const handleRowChick = (row, column) => {
  //阻止行内点击与操作按钮点击冲突，希望点击按钮不会变色/选中
  if (column && column.label == "操作") {
    return;
  }
  const selected = assetsSelection.value.some((item) => item.assetsId === row.assetsId);
  if (!selected) {
    assetsSelection.value.push(row);
    assetsTableRef.value.toggleRowSelection(row);
  } else {
    const finArr = assetsSelection.value.filter((item) => {
      return item.assetsId !== row.assetsId;
    });
    assetsSelection.value = finArr;
    assetsTableRef.value.toggleRowSelection(row, false);
  }
};
//点击高亮
const getRowClass = ({ row }) => {
  return proxy.rowClass(row, assetsSelection.value, "assetsId");
};

///2打开可添加的资产数据对话框
const canUseAddInfo = ref({
  openObj: {
    visible: false,
    openTitle: t("assetsList.assetsList"),
  },
  columns: columns,
});

const openAssetsListDialog = async () => {
  console.log("需要打开资产查询的对话框，根据不同查询返回结果", canUseAddInfo);
  canUseAddInfo.value.openObj.visible = true;
  await getCanUseAssetsData();
};
//查询可选择的列表，这里也是需要从父组件传值过来查询，
const getCanUseAssetsData = () => {
  emit("getCanUseAssetsData");
};

const getSubmitSend = (val) => {
  // 更新父组件的tableData
  // 被取消勾选的数据（state 为 0）会被移除，而新的选择状态会被合并到现有的数据中，确保数据同步一致。
  // 1.过滤出state=1的项目 为了让state=0的数据在取消勾选的时候可以移除
  proxy.addEditInfo.tableData = proxy.addEditInfo.tableData.filter(
    (item) => item.state === 1
  );
  //2循环
  val.forEach((item) => {
    const existingIndex = proxy.addEditInfo.tableData.findIndex(
      (e) => e.assetsId === item.assetsId
    );
    if (existingIndex !== -1) {
      // 如果 `tableData` 中已经存在相同的 `assetsId`，则更新该项
      proxy.addEditInfo.tableData[existingIndex] = item;
    } else {
      // 如果 `tableData` 中不存在相同的 `assetsId`，则新增该项
      proxy.addEditInfo.tableData.push(item);
    }
  });
};
// 获取默认选中的资产列表
const getSelectedAssets = () => {
  return proxy.addEditInfo.tableData.map((item) => item.assetsId);
};

//3查看资产详情

const assetsDetailInfo = reactive({
  openObj: {
    visible: false,
    openTitle: "",
  },
  form: {},
});
const openAssetsDetail = (row) => {
  assetsDetailInfo.openObj = {
    visible: true,
    openTitle: "资产详情",
  };
  assetsDetailInfo.form = row;
  console.log("点击详情", row, assetsDetailInfo);
};

const getDisAbled = (key, disabled) => {
  if (key == "add") return false;
  if (key == "edit" && disabled) return true;
  if (key == "reapply" && disabled) return true;
  if (key == "detail") return true;
  if (key == "return") return true;
};

defineExpose({ resetAddOrEdit, canUseAddInfo });
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";
.dialog_title {
  display: flex;
  font-weight: 700;

  .blueLine {
    color: #1065ff;
    background: #1065ff;
    width: 5px;
    height: auto;
    border-radius: 3px;
    margin-right: 10px;
  }
  .title {
    color: #000;
  }
}
.flex_title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  .left_title {
    color: $--color-primary;
    font-weight: bold;
  }
}
</style>
